<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮播图.</title>
    <script src="./dist/testcss.js"></script>
    <link rel="stylesheet" href="./css/demo.css">
</head>

<body>
    <div class="banner">
        <ul>
            <li><img src="./1.jpg" alt=""></li>
            <li><img src="./2.jpg" alt=""></li>
            <li><img src="./3.jpg" alt=""></li>
            <li><img src="./4.jpg" alt=""></li>
            <li><img src="./5.jpg" alt=""></li>
        </ul>
        <ol>
            <li class="active">1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ol>
    </div>
    <script src="./jquery-3.6.0.min.js"></script>
    <script>
        $(function () {
            var ulLi = $(".banner>ul>li");//5
            //克隆第一个图片到最后
            ulLi.first().clone().appendTo(".banner>ul");
            var index = 0;//图片下标
            var timmerID;
            autoPlay();
            $(".banner").mouseenter(function () {
                clearInterval(timmerID);
            });
            $(".banner").mouseleave(function () {
                autoPlay();
            });
            $(".banner>ol>li").click(function () {
                index = $(this).index();
                play();
            });
            function play() {
                if (index < 0) {//判断第一张的上一张
                    index = ulLi.length - 1;
                }
                var imgW = $(".banner>ul img").width();
                var ulLeft = -(index * imgW);
                if (index >= ulLi.length) {//设置当最后一个张图滚动时，第一个选中.
                    $(".banner>ol>li").removeClass("active").eq(0).addClass("active");
                } else {
                    $(".banner>ol>li").removeClass("active").eq(index).addClass("active");
                }

                $("ul").stop(true).animate({ left: ulLeft }, function () {
                    //滚动完成以后
                    if (index >= ulLi.length) {
                        //如果是到达了最后一张，设置index=0 设置left=0
                        //等最后一张（第一张）滚动完成立即切换显示第一张
                        index = 0;
                        $(this).css({ left: 0 });
                    }
                });
            }
            function autoPlay() {
                timmerID = setInterval(function () {
                    index++;
                    play();
                }, 2500)
            }
        });
    </script>
</body>

</html>